/**
 * Copyright (C), 2015-2018
 * FileName: DubboServicePlugin
 * Author:   Dayu Hou
 * Date:     2018/1/17 9:13
 * Description: 类似dubbo接口
 * History:
 * <author>          <time>         <desc>
 */
package com.apache.rpc.service.plugins;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.exception.BusinessException;
import com.apache.exception.ServiceException;
import com.apache.rpc.ProtocolService;
import com.apache.rpc.client.ProtocolAdapter;
import com.apache.rpc.entity.Protocol;
import com.apache.rpc.entity.RpcMonitoring;
import com.apache.rpc.service.monitoring.MonitoringDataBaseHelper;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;

import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 * 〈类似dubbo接口〉
 *
 * @author Dayu Hou
 * @since 1.0.0
 */
public class DubboServicePlugin implements PluginConnector {

    private ProtocolService protocolAdapter;

    public Object execute(ParamsVo param) throws Exception {
        String methodKey = String.valueOf(param.getParams("MethodCode"));
        String beanId = String.valueOf(param.getParams("BeanId"));
        if (Validator.isNull(methodKey) || Validator.isNull(beanId)) {
            ResultEntity entity = getResultEntity("方法参数为空，不能被正确访问");
            return entity;
        }
        String socketClose = "false";
        Map<String, Object> maps = param.getParams();
        maps.remove("MethodCode");
        maps.remove("BeanId");
        ResultEntity entity = doService(beanId, methodKey, maps);
        return entity;
    }

    private ResultEntity doService(String beanId, String methodName, Map<String, Object> params) {
        String startTime = DateUtils.Now.fmt_yyyyMMdd_HHmmssSSS();
        Protocol protocol = new Protocol();
        protocol.setBeanId(beanId);
        protocol.setRespType("xml");
        protocol.setReqFlag(methodName);
        String requestsource = String.valueOf(params.get("requestSources"));
        params.remove("requestSources");
        if (params != null && !params.isEmpty()) {
            protocol.setParams(params);
        }
        ResultEntity resultEntity = null;
        try {
            String result = getProtocolAdapter().doServiceStr(protocol);
            if (Validator.isNull(result)) {
                resultEntity = getResultEntity("接口调用超时");
            } else {
                resultEntity = new ResultEntity();
                resultEntity.setResult("true");
                resultEntity.setEntity(result);
                resultEntity.setMessage("执行成功");
            }
        } catch (ServiceException e) {
            resultEntity = getResultEntity("执行远程调用接口出错:" + e.getMessage());
        } catch (BusinessException e1) {
            resultEntity = getResultEntity(e1.getMessage());
        }
        String stopTime = DateUtils.Now.fmt_yyyyMMdd_HHmmssSSS();
        writeMonitoring(startTime, stopTime, protocol, requestsource);
        return resultEntity;
    }

    private ResultEntity getResultEntity(String message) {
        ResultEntity resultEntity = new ResultEntity();
        resultEntity.setResult("false");
        resultEntity.setMessage(message);
        return resultEntity;
    }

    public void writeMonitoring(String startTime, String stopTime, Protocol protocol,
            String requestSources) {
        RpcMonitoring monitoring = new RpcMonitoring();
        monitoring.setBeanId(protocol.getBeanId());
        monitoring.setMethodKey(protocol.getReqFlag());
        Map map = protocol.getParams();
        if (null != map || !map.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            if (StrUtil.isNotNull(String.valueOf(map.get("Client-IP")))) {
                sb.append(String.valueOf(map.get("Client-IP")) + "->");
            }
            if (StrUtil.isNotNull(String.valueOf(map.get("requestIp")))) {
                sb.append(String.valueOf(map.get("requestIp")) + "->");
            }
            sb.append(String.valueOf(map.get("rpcExeTimeAddr")));
            if (StrUtil.isNotNull(String.valueOf(map.get("rpcExeTimePort")))) {
                sb.append(":" + String.valueOf(map.get("rpcExeTimePort")));
            }
            monitoring.setServerAddr(sb.toString());
            map.remove("rpcExeTimeAddr");
            map.remove("Client-IP");
            map.remove("rpcExeTimePort");
            monitoring.setReqParams(map.toString());
        }
        monitoring.setMonitoring1(requestSources);//请求源
        monitoring.setStartTime(startTime);
        monitoring.setStopTime(stopTime);
        MonitoringDataBaseHelper.getInstance().exeMonitoring(monitoring);
    }

    public ProtocolService getProtocolAdapter() {
        if (null == protocolAdapter) {
            this.protocolAdapter = ProtocolAdapter.getAdapter();
        }
        return this.protocolAdapter;
    }
}